package socket5

import (
	"errors"
	"io"
	"net"
)

var (
	ERROR_SOCKET_VERSION_SUPPORTED = errors.New("不支持该socket版本")
	ERROR_COMMAND_NOT_SUPPORTED    = errors.New("不支持该COMMAND命令")
	ERRADDRESS_TYPE_NOT_SUPPORTED  = errors.New("不支持该地址类型")
)

const (
	SOCKET_5_VERSION       = 0x05
	Method_NO_AUTH         = 0x00
	Method_GSS_API         = 0x01
	Method_PASS_WORD       = 0x02
	Method_NO_ACCEPT_TABLE = 0xff
	ReservedFild           = 0x00
)

type Method = byte

type ClientAuthMessage struct {
	Version byte

	NMethods byte

	Methods []Method
}

func NewServerAuthMessage(conn net.Conn, method Method) error {
	buf := []byte{SOCKET_5_VERSION, method}
	_, err := conn.Write(buf)
	return err
}

func NewClientAuthMessage(conn net.Conn) (*ClientAuthMessage, error) {

	//读取socket版本
	buf := make([]byte, 2)
	_, err := io.ReadFull(conn, buf)
	if err != nil {
		return nil, err
	}
	//校验socket 版本
	if buf[0] != SOCKET_5_VERSION {
		return nil, ERROR_SOCKET_VERSION_SUPPORTED
	}

	//读取method
	nmethos := buf[1]

	buf = make([]byte, nmethos)
	_, err = io.ReadFull(conn, buf)

	if err != nil {
		return nil, err
	}

	return &ClientAuthMessage{
		Version:  SOCKET_5_VERSION,
		NMethods: nmethos,
		Methods:  buf,
	}, nil
}
